package com.shengsiyuan.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述：服务端
 *
 * @author: lpf
 * @date: 2019/6/21 17:25
 * @version: 1.0
 */
public class GrpcServer {

    private Server server;

    private void start() throws IOException {
        this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start();
        System.out.println("server started!");

        // 这里有个问题未解决：Process 'command 'C:/DevelopTools/Java/jdk1.8.0_131/bin/java.exe'' finished with non-zero exit value 1
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("关闭jvm");
            GrpcServer.this.stop();
        }));

        System.out.println("执行到这里");
    }

    private void stop() {
        if (this.server != null) {
            this.server.shutdown();
        }
    }

    private void awaitTermination() throws InterruptedException {
        if (this.server != null) {
            this.server.awaitTermination();
            //this.server.awaitTermination(3000, TimeUnit.MILLISECONDS);
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        GrpcServer server = new GrpcServer();
        server.start();
        server.awaitTermination(); // 不加这行代码，服务一启动就会退出，不会阻塞等待
    }
}
